package com.zt.rongda.reimburse.service;

import java.util.List;

import com.zt.bpm.model.FormEntity;
import com.zt.bpm.service.*;
import com.zt.org.inter.DepartmentMapper;
import com.zt.rongda.constant.BusConstant;
import com.zt.rongda.employee.inter.EmployeeMapper;
import com.zt.rongda.employee.model.Employee;
import com.zt.rongda.reimburse.inter.ReimburseBillMapper;
import com.zt.rongda.reimburse.model.ReimburseBill;
import com.zt.shiro.GlobalInput;
import com.zt.system.model.BusinessException;
import com.zt.servlet.ReqBean;
import com.zt.system.model.SqlBuilder;
import com.zt.system.service.BaseService;
import com.zt.util.StringUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;

@Service
public class ReimburseBillService extends DZFormService {

    public final static String BEAN_ID = "reimburseBillService";

    @Autowired
    private ReimburseBillMapper reimburseBillMapper;

    @Autowired
    private ProcessService processService;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private DepartmentMapper departmentMapper;

    @Autowired
    private TasksService tasksService;

    /**
    * 查询
    *
    * @param reqBean
    * @return
    */
    public JSONObject getTable(ReqBean reqBean) {
        SqlBuilder sqlBuilder = new SqlBuilder("");
        sqlBuilder.appendSql("select a.*,d.DEPT_NAME,e.EMP_NAME from REIMBURSE_BILL a " +
                "LEFT JOIN SYS_DEPARTMENT d ON d.DEPT_ID = a.DEPT_ID " +
                "LEFT JOIN EMPLOYEE e ON e.EMP_ID = a.EMP_ID where 1=1 ");
        sqlBuilder.addWhere("a.ORDER_ID", reqBean.getInfo("orderId"));
        if(StringUtil.isNotEmpty(reqBean.getInfo("status"))) {
            sqlBuilder.addWhereIn("a.STATUS",reqBean.getInfo("status").split(","));
        }
        return queryTable(sqlBuilder, reqBean.getPageSize(), reqBean.getPageIndex());
    }

    /**
    * 通过id查询
    *
    * @param reimburseId
    * @return
    */
    public ReimburseBill getById(String reimburseId) {
        return reimburseBillMapper.selectByPrimaryKey(reimburseId);
    }

    /**
    * 新增
    *
    * @param reimburseBill
    */
    public void add(ReimburseBill reimburseBill) {
        reimburseBill.setReimburseId(intIncrementId("REIMBURSE_BILL","REIMBURSE_ID"));// 手动设置Id
        reimburseBill.setStatus(BusConstant.ReimburseBill.STATUS_UNCHECK);
        reimburseBill.setMakeTime(new Date());
        reimburseBill.setModifyTime(reimburseBill.getMakeTime());
        reimburseBillMapper.insert(reimburseBill);
    }

    /**
    * 修改
    *
    * @param reimburseBill
    */
    public void update(ReimburseBill reimburseBill) {
        String reimburseId = reimburseBill.getReimburseId();
        if (StringUtil.isEmpty(reimburseId)) {
            throw new BusinessException("获取主键失败");
        }

        reimburseBill.setModifyTime(new Date());
        reimburseBillMapper.updateByPrimaryKeySelective(reimburseBill);
    }


    @Override
    public JSONObject toJSONObject(String id) {
        ReimburseBill reimburseBill = reimburseBillMapper.selectByPrimaryKey(id);
        return reimburseBill.toJsonObject();
    }

    /**
    * 删除
    *
    * @param reimburseId
    */
    public void delete(String reimburseId) {
        if (StringUtil.isEmpty(reimburseId)) {
            throw new BusinessException("获取主键失败");
        }
        reimburseBillMapper.deleteByPrimaryKey(reimburseId);
    }



    /**
     * 提交申请
     * @param reimburseId
     */
    public void apply(String reimburseId) {
        if (StringUtil.isEmpty(reimburseId)) {
            throw new BusinessException("非法请求");
        }
        ReimburseBill reimburseBill = reimburseBillMapper.selectByPrimaryKey(reimburseId);
        reimburseBill.setStatus(BusConstant.ReimburseBill.STATUS_APPLY);
        reimburseBill.setOperator(GlobalInput.getCurrentUserId());
        reimburseBill.setModifyTime(new Date());
        reimburseBillMapper.updateByPrimaryKey(reimburseBill);

        Employee employee = employeeMapper.selectByPrimaryKey(reimburseBill.getEmpId());

        //启动报销审批流程
        String title = String.format("[%s]%s", employee.getName(),reimburseId);
        processService.startProcessByKey(BusConstant.REIMBURSE_BILL_AUDIT_KEY,
                title, reimburseBill.toJsonObject().toString(), GlobalInput.getCurrentUserId());
    }

    /**
     * 报销审批
     * @param reimburseId
     * @param remark
     */
//    public void reimburseCheck(String reimburseId, String remark) {
//        if(StringUtil.isEmpty(reimburseId)) {
//            throw new BusinessException("非法请求!");
//        }
//        ReimburseBill reimburseBill = reimburseBillMapper.selectByPrimaryKey(reimburseId);
//        reimburseBill.setStatus(BusConstant.ReimburseBill.STATUS_CHECKED);
//        reimburseBill.setOperator(GlobalInput.getCurrentUserId());
//        reimburseBill.setModifyTime(new Date());
//        reimburseBill.setRemark(remark);
//        reimburseBillMapper.updateByPrimaryKey(reimburseBill);
//    }

    /**
     * 审批待办列表
     * @param reqBean
     * @return
     */
    public JSONObject getTasks(ReqBean reqBean) {
        reqBean.addInfo("processDefinitionKey", BusConstant.REIMBURSE_BILL_AUDIT_KEY);
        JSONObject result = tasksService.getTasks(reqBean);
        JSONArray tasks = (JSONArray) result.get("rows");

        for (Object taskObj : tasks) {
            JSONObject task = (JSONObject) taskObj;
            JSONObject processInstance = task.containsKey("processInstance") ? task.getJSONObject("processInstance")
                    : null;
            if (processInstance != null) {
                String businessKey = processInstance.containsKey("businessKey") ? processInstance
                        .getString("businessKey") : null;
                if (!StringUtil.isEmpty(businessKey)) {
                    String reimburseId = FormFactory.getBusinessId(businessKey);
                    ReimburseBill reimburseBill = reimburseBillMapper.selectByPrimaryKey(reimburseId);
                    JSONObject json = reimburseBill.toJsonObject();
                    json.put("empName",employeeMapper.selectByPrimaryKey(reimburseBill.getEmpId()).getName());
                    json.put("deptName",departmentMapper.selectByPrimaryKey(reimburseBill.getDeptId()).getName());
                    task.put("reimburseBill", json);
                    task.put("processInstance", processInstance);
                }
            }
        }
        return result;
    }
}